package com.wt.admin.controller;

import com.aizuda.easy.security.domain.Rep;
import com.aizuda.easy.security.exp.impl.BasicException;
import com.wt.admin.service.file.FileService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;


@RequestMapping("upload")
@RestController
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    @PostMapping("/toLocal")
    public Rep<String> uploadLocal(@RequestParam("file") MultipartFile file, @RequestParam("path") String path, HttpServletRequest httpServletRequest) throws IOException {
        return Rep.ok(fileService.uploadLocal(file,path,httpServletRequest));
    }
    @PostMapping("/uploadStrategy")
    public Rep<String> uploadStrategy(@RequestParam("file") MultipartFile file,@RequestParam("path") String path,HttpServletRequest httpServletRequest ) throws IOException, BasicException {
        return Rep.ok(fileService.uploadStrategy(file, path, httpServletRequest));
    }


    @PostMapping("/uploadLocalBatch")
    public Rep<List<String>> uploadLocalBatch(@RequestParam("file") MultipartFile[] file, @RequestParam("path") String path, HttpServletRequest httpServletRequest) {
        return Rep.ok(fileService.uploadLocalBatch(file, path, httpServletRequest));
    }
    @PostMapping("/uploadStrategyBatch")
    public Rep<List<String>> uploadStrategyBatch(@RequestParam("file") MultipartFile[] file, @RequestParam("path") String path, HttpServletRequest httpServletRequest ) throws IOException, BasicException {
        return Rep.ok(fileService.uploadStrategyBatch(file, path, httpServletRequest));
    }


    @PostMapping("/chunk")
    public Rep<?> uploadChunk(
            @RequestParam("file") MultipartFile file,
            @RequestParam("fileHash") String fileHash,
            @RequestParam("fileName") String fileName,
            @RequestParam("chunkIndex") int chunkIndex,
            @RequestParam("totalChunks") int totalChunks
    ){
        fileService.saveChunk(file, fileHash, fileName, chunkIndex, totalChunks);
        return Rep.ok();
    }

    @PostMapping("/exists")
    public Rep<List<Integer>> checkExistingChunks(@RequestBody Map<String,String> map) {
        return Rep.ok(fileService.getExistingChunks(map.get("fileHash")));
    }

    @PostMapping("/merge")
    public Rep<String> mergeChunks(@RequestBody MergeRequest request) {
        return Rep.ok(fileService.mergeChunks(request));
    }

    @Data
    public static class MergeRequest {
        private String fileHash;
        private String fileName;
        private String path;
        private int totalChunks;
    }

}
